package org.gaaidou.ptarmigan.springboot.functional.vo;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.gaaidou.ptarmigan.springboot.core.BaseBean;
import org.gaaidou.ptarmigan.springboot.functional.bean.Experience;
import org.gaaidou.ptarmigan.springboot.functional.bean.Gender;
import org.gaaidou.ptarmigan.springboot.functional.bean.User;
import org.gaaidou.ptarmigan.springboot.idworker.IdWorker;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class UserVo extends BaseBean {
    private long id;

    @NotBlank
    private String name;
    @NotBlank
    private String password;

    private String mobile;

    private Gender gender;

    @NotNull
    private Date birthday;

    @NotEmpty
    private List<@Valid ExperienceVo> experiences;

    public User toUser(IdWorker<Long> idWorker, Date now, String createUser) {
        User user = new User();
        BeanUtils.copyProperties(this, user);
        user.setCreateTime(now.getTime());
        user.setCreateUser(createUser);
        user.setUpdateTime(now.getTime());
        user.setUpdateUser(createUser);
        user.setId(idWorker.nextId());
        List<Experience> experiences = this.getExperiences().stream().map(experienceVo -> {
            Experience experience = new Experience();
            BeanUtils.copyProperties(experienceVo, experience);
            experience.setRole(experienceVo.getRoles().get(0));
            experience.setUser(user);
            experience.setId(idWorker.nextId());
            experience.setCreateTime(now.getTime());
            experience.setCreateUser(createUser);
            experience.setUpdateTime(now.getTime());
            experience.setUpdateUser(createUser);
            return experience;
        }).toList();
        user.setExperiences(experiences);

        return user;
    }

    public UserVo(User user) {
        BeanUtils.copyProperties(user, this);
        List<ExperienceVo> experiences = user.getExperiences().stream().map(v -> {
            ExperienceVo experienceVo = new ExperienceVo();
            BeanUtils.copyProperties(v, experienceVo);
            experienceVo.setRoles(List.of(v.getRole()));
            return experienceVo;
        }).toList();
        this.setExperiences(experiences);
    }
}
